package com.syh.jn.scm.domain.downstream.entity.purchase;


import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.spring.SpringContextUtils;
import cn.redscarf.commons.util.validator.ValidationUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.domain.AbstractSimpleAggregate;
import com.syh.core.ddd.domain.CodeExpEnum;
import com.syh.core.ddd.domain.CodeGenerateUtil;
import com.syh.jn.scm.domain.downstream.entity.logistics.DownLogisticsBill;
import com.syh.jn.scm.domain.downstream.repository.logistics.DownLogisticsBillReadRepository;
import com.syh.jn.scm.dto.downstream.purchase.DownPurchaseReturnOrderMto;
import com.syh.jn.scm.dto.downstream.purchase.DownPurchaseReturnOrderSto;
import com.syh.jn.scm.dto.support.FilesDto;
import com.syh.jn.scm.exception.BusinessException;
import com.syh.jn.scm.service.api.downstream.logistics.enums.DownLogisticsBillEnums;
import com.syh.jn.scm.service.api.downstream.purchase.enums.DownPurchaseOrderEnums;
import com.syh.jn.scm.service.api.downstream.purchase.enums.DownPurchaseReturnOrderEnums;
import com.syh.jn.scm.service.api.supplier.logistics.enums.LogisticsBillEnums;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Date:2018/7/2
 * Author:Clown
 * 下游采购退货单;
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class DownPurchaseReturnOrder extends AbstractSimpleAggregate<Long> {
  public DownPurchaseReturnOrder(Long id) {
    this.id = id;
  }

  /**
   * 下游创建新退货单
   *
   * @param dto
   * @return
   */
  public static DownPurchaseReturnOrder createdByDownStream(DownPurchaseReturnOrderSto dto) {
    ValidationUtils.validate(dto);
    //创建订单(设置状态)
    DownPurchaseReturnOrder order = DownPurchaseReturnOrder.commonCreatePurRetOrder(Short.valueOf("1"));
    order.setCode(CodeGenerateUtil.codeGenerate(CodeExpEnum.SALES_RETURN_ORDER_EXP.getCodeExp(), dto.getDownStreamCompanyId()));
    order.setUuid(UUID.randomUUID().toString());
    ExtAssert.notNull(dto.getItems(), "明细对象为空");
    ExtBeanUtils.copyProperties(dto, order, false);
    order.items = new ArrayList<>();
    dto.getItems().stream().forEach(itemSto -> {
      ValidationUtils.validate(itemSto);
      order.addItem(new DownPurchaseReturnOrderItem(itemSto));
    });
    //计算退货单总额，这里的退货单总额是刚提交时供应商还未确认，不包括运费
    order.calculateTotalAmount();

    return order;
  }

  /**
   * 下游修改采购退货单
   *
   * @param mto
   */
  public void modify(DownPurchaseReturnOrderMto mto, DownPurchaseReturnOrder order) {
    ExtAssert.notNull(mto, "对象为空");
    //采购退货单已确认则不可修改
    if (order.getReturnOrdState().equals(DownPurchaseReturnOrderEnums.OrdState.CONFIRM.getStatus())) {
      throw new BusinessException("订单已经确认,不可以修改");
    }
    ExtBeanUtils.copyProperties(mto, this, false);
    this.items = new ArrayList<>();
    mto.getItems().stream().forEach(itemMto -> {
      this.addItem(new DownPurchaseReturnOrderItem(itemMto));
    });
    this.calculateTotalAmount();
  }

  /**
   * 创建订单
   *
   * @return purRetOrder 采购退货单
   */
  private static DownPurchaseReturnOrder commonCreatePurRetOrder(Short createdType) {
    DownPurchaseReturnOrder order = new DownPurchaseReturnOrder();
    order.returnOrdState = DownPurchaseReturnOrderEnums.OrdState.STAYCONFIRM.getStatus();
    order.generatedState = DownPurchaseReturnOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    order.deliveryState = DownPurchaseReturnOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
    order.collectState = DownPurchaseReturnOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus();
    order.createType = createdType;
    order.discount = BigDecimal.ZERO;//设置优惠减免的默认值为0
    order.totalFreight = BigDecimal.ZERO;//设置运费总额的默认值为0
    order.createTimeStamp = System.currentTimeMillis();
    order.inputDateTimestamp = System.currentTimeMillis();
    return order;
  }

  /**
   * 增加订单项
   *
   * @param item
   * @return
   */
  public DownPurchaseReturnOrder addItem(DownPurchaseReturnOrderItem item) {
    if (this.items == null) {
      this.items = new ArrayList<>();
    }
    this.items.add(item);
    return this;
  }

  /**
   * 删除订单项
   *
   * @param item
   * @return
   */
  public DownPurchaseReturnOrder deleteItem(DownPurchaseReturnOrderItem item) {
    if (item.getSaleReturnOrderId().equals(this.id)) {
      this.items.remove(item);
    }
    return this;
  }

  /**
   * 计算退货单总额和商品总额
   */
  public void calculateTotalAmount() {
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (DownPurchaseReturnOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.getReturnTotalAmount());
    }
    this.returnTotalGoodsAmount = totalAmount;//商品总额
    if (this.discount != null) {
      totalAmount = totalAmount.subtract(this.discount);
    }
    this.returnTotalAmount = totalAmount;//订单总额
  }

  /**
   * 计算退货单发货总额和商品发货总额
   */
  public void calculateTotalReturnOutAmount() {
    //计算订单已出库商品总额
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (DownPurchaseReturnOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.calculateTotalReturnOutAmount());
    }
    this.returnTotalOutGoodsAmount = totalAmount;

    //先计算出该订单下已发出、已签收状态的物流单据的物流费用
    DownLogisticsBillReadRepository logisticsBillReadRepository = (DownLogisticsBillReadRepository) SpringContextUtils.getBean(DownLogisticsBillReadRepository.class);
    Wrapper we = Wrapper.build();
    we.append(Restrictions.eq("orderId", this.id));
    we.append(Restrictions.eq("orderType", DownLogisticsBillEnums.OrderType.RETURN_PURCHASE.getStatus()));
    we.append(Restrictions.or(Restrictions.eq("logisticsState", LogisticsBillEnums.State.DELIVEED.getStatus()),
            Restrictions.eq("logisticsState", LogisticsBillEnums.State.SIGNIN.getStatus())));
    List<DownLogisticsBill> logisticsBills = logisticsBillReadRepository.getList(we);

    BigDecimal logisticsBillBeforeBuyFreight = BigDecimal.ZERO;//物流单据为预收买家的所有物流费用
    for (DownLogisticsBill logisticsBill : logisticsBills) {
      if (logisticsBill.getFreightTake() != null && logisticsBill.getFreightTake().equals(LogisticsBillEnums.FreightTake.BUY.getStatus())
              && logisticsBill.getFreightType().equals(LogisticsBillEnums.FreightType.BEFORE.getStatus())) {
        logisticsBillBeforeBuyFreight = logisticsBillBeforeBuyFreight.add(logisticsBill.getTotalFreight());
      }
    }

    //加上预收买家的物流运费
    totalAmount = totalAmount.add(logisticsBillBeforeBuyFreight);
    //计算订单已出库订单总额
    if (this.discount != null) {
      totalAmount = totalAmount.subtract(this.discount);
    }
    this.totalFreight = logisticsBillBeforeBuyFreight;
    this.returnTotalOutAmount = totalAmount.compareTo(BigDecimal.ZERO) < 1 ? BigDecimal.ZERO : totalAmount;
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /**
   * 计算退货单发货状态
   */
  public void calculateDeliveryStatus() {
    this.deliveryState = DownPurchaseReturnOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus();
    //默认标记为未发货
    boolean unDelivery = true;

    //计算订单已出库商品总额
    for (DownPurchaseReturnOrderItem item : this.items) {
      //订单项已发货数量小于订单数量则为部分发货
      if (this.deliveryState.equals(DownPurchaseReturnOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus())
              && item.getReturnOutedQuantity().compareTo(item.getReturnQuantity()) < 0) {
        this.deliveryState = DownPurchaseReturnOrderEnums.DeliveryState.LOGISTICS_PART_DELIVEED.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unDelivery && item.getReturnOutedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unDelivery = false;
      }
    }
    if (unDelivery) {
      this.deliveryState = DownPurchaseReturnOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
      this.deliveryTimestamp = null;
    }
  }

  /**
   * 取消采购退货单
   */
  public void cancel() {
    //只有订单状态为待确认的订单才能取消
    if (!this.getReturnOrdState().equals(DownPurchaseReturnOrderEnums.OrdState.STAYCONFIRM.getStatus())) {
      logger.error("cancel:退货单状态不为待确认，不能取消");
      throw new RuntimeException("cancel:退货单状态不为待确认，不能取消");
    }
    this.returnOrdState = DownPurchaseReturnOrderEnums.OrdState.CANCEL.getStatus();
  }

  /**
   * 删除采购退货单
   */
  public void destroy() {
    //只有订单状态为待确认或者已取消的才能删除
    if (!this.getReturnOrdState().equals(DownPurchaseReturnOrderEnums.OrdState.CANCEL.getStatus())) {
      throw new BusinessException("订单不是已取消状态,不可以删除");
    }
    if (this.haveRecord != null &&
            this.haveRecord.equals(DownPurchaseReturnOrderEnums.HaveRecord.HAVE_RECORD.getStatus())) {
      throw new BusinessException("订单已存在记录,不可以删除");
    }

  }

  /**
   * 记录已生成物流数量
   *
   * @param logisticsBill
   * @param operate       (1为增加记录，2为减少记录)
   */
  public void countGeneratedQuantity(DownLogisticsBill logisticsBill, int operate) {
    if (operate == 1) {
      logisticsBill.getItems().forEach(logisticsBillItem -> {
        this.items.forEach(orderItem -> {
          if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
            orderItem.setGeneratedQuantity(orderItem.getGeneratedQuantity() == null ? logisticsBillItem.getQuantity() :
                    orderItem.getGeneratedQuantity().add(logisticsBillItem.getQuantity()));
            //如果当前生成发货数量大于退货总数 则不允许生成
            if (orderItem.getGeneratedQuantity().compareTo(orderItem.getReturnQuantity()) > 0) {
              throw new BusinessException("发货失败：超出退货数量！" + orderItem.getGoodsName() + "退货数量" + orderItem.getReturnQuantity() + ";已退货数量" + orderItem.getGeneratedQuantity().subtract(logisticsBillItem.getQuantity()));
            }
          }
        });
      });
    } else {
      logisticsBill.getItems().forEach(logisticsBillItem -> {
        this.items.forEach(orderItem -> {
          if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
            orderItem.setGeneratedQuantity(orderItem.getGeneratedQuantity().subtract(logisticsBillItem.getQuantity()));
          }
        });
      });
    }

    //默认为已完全生成物流单
    this.generatedState = DownPurchaseReturnOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus();
    //默认标记为未生成物流单
    boolean unGenerated = true;

    for (DownPurchaseReturnOrderItem item : this.items) {
      //订单项已生成数量小于订单数量则为部分生成物流单
      if (this.generatedState.equals(DownPurchaseReturnOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus())
              && item.getGeneratedQuantity().compareTo(item.getReturnQuantity()) < 0) {
        this.generatedState = DownPurchaseReturnOrderEnums.GeneratedState.LOGISTICS_PART_GENERATE.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unGenerated && item.getGeneratedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unGenerated = false;
      }
    }
    if (unGenerated) {
      this.generatedState = DownPurchaseReturnOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    }
  }

  /**
   * 发货信息更新
   */
  public void delivery(DownLogisticsBill bill) {
    if (this.deliveryState.equals(DownPurchaseOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus()))
      throw new BusinessException("发货失败，已全部发货！");
    //修改订单项发货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setReturnOutedQuantity(orderItem.getReturnOutedQuantity() == null ? logisticsBillItem.getQuantity() :
                  orderItem.getReturnOutedQuantity().add(logisticsBillItem.getQuantity()));

        }
      });
    });

    this.deliveryTimestamp = System.currentTimeMillis();
    this.calculateTotalReturnOutAmount();
    this.calculateDeliveryStatus();
  }

  /**
   * 取消发货信息更新
   */
  public void cancelDelivery(DownLogisticsBill bill) {
    if (this.deliveryState.equals(DownPurchaseOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus()))
      throw new BusinessException("取消发货失败，无发货记录！");
    //修改订单项发货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setReturnOutedQuantity(orderItem.getReturnOutedQuantity().subtract(logisticsBillItem.getQuantity()));
        }
      });
    });
    this.calculateTotalReturnOutAmount();
    this.calculateDeliveryStatus();
  }

  /**
   * 生成对账单
   */
  public void generating(Long statementOfAccountId) {
    if (this.collectState.equals(DownPurchaseReturnOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus())) {
      throw new BusinessException("采购单退货单" + this.code + "未签收，无法生成对账单");
    }
    if (this.returnOrdState.equals(DownPurchaseReturnOrderEnums.OrdState.STATEMENT.getStatus())) {
      throw new BusinessException("销售单已生成对账单!");
    }
    this.statementId = statementOfAccountId;
    this.returnOrdState = DownPurchaseReturnOrderEnums.OrdState.STATEMENT.getStatus();
  }

  /**
   * 取消对账单
   */
  public void cancelGenerating() {
    if (this.returnOrdState.equals(DownPurchaseReturnOrderEnums.OrdState.CONFIRM.getStatus())) {
      throw new BusinessException("销售单已取消对账单!");
    }
    this.statementId = null;
    this.returnOrdState = DownPurchaseReturnOrderEnums.OrdState.CONFIRM.getStatus();
  }

  /**
   * 下游采购退货订单上传图片
   *
   * @param dto
   */
  public void upload(FilesDto dto) {
    this.secondSrcImages = dto.getFiles();
  }

  /**
   * 销售退货单编号
   */
  private String code;
  /**
   * 第三方订单号
   */
  private String extCode;
  /**
   * 对应销售单id
   */
  private Long saleOrderId;
  /**
   * 归属id
   */
  private Long businessEntityId;
  /**
   * 对应对账单id
   */
  private Long statementId;
  /**
   * 退货单状态(0：待确认 1：已确认 2：挂起 3：已生成对账单 -1：已取消)
   */
  private Short returnOrdState;
  /**
   * 订单创建类型(字典获取 fixed 0：服务商录入 1:客户录入 2：对接客户系统 3：系统自动)
   */
  private Short createType;
  /**
   * 下游购买单位ID
   */
  private Long downStreamCompanyId;
  /**
   * 备注
   */
  private String remark;
  /**
   * 订单总额
   */
  private BigDecimal totalAmount;
  /**
   * 退货订单总额
   */
  private BigDecimal returnTotalAmount;
  /**
   * 退货订单商品总额
   */
  private BigDecimal returnTotalGoodsAmount;
  /**
   * 退货出库总额
   */
  private BigDecimal returnTotalOutAmount;
  /**
   * 退货出库商品总额
   */
  private BigDecimal returnTotalOutGoodsAmount;
  /**
   * 退货签收总额
   */
  private BigDecimal returnTotalInAmount;
  /**
   * 退货签收商品总额
   */
  private BigDecimal returnTotalInGoodsAmount;
  /**
   * 优惠减免
   */
  private BigDecimal discount;
  /**
   * 运费金额
   */
  private BigDecimal totalFreight;
  /**
   * 录入日期
   */
  private Long inputDateTimestamp;
  /**
   * 发货时间
   */
  private Long deliveryTimestamp;
  /**
   * 预计到达时间
   */
  private Long etaDateTimestamp;
  /**
   * 录单人ID
   */
  private Long operatorId;
  /**
   * 收货人姓名
   */
  private String deliName;
  /**
   * 收货人联系电话
   */
  private String deliTel;
  /**
   * 收货地区编码
   */
  private String deliAreaCode;
  /**
   * 收货地址省市区
   */
  private String deliArea;
  /**
   * 收货人详细地址
   */
  private String deliAddress;
  /**
   * 退货原因id
   */
  private Long returnReasonId;
  /**
   * 退货入库时间
   */
  private Long depotTimestamp;
  /**
   * 物流生成状态(0：未生成物流单 1：部分生成物流单2：完成生成物流单)
   */
  private Short generatedState;
  /**
   * 发货状态(0：未发货 1：部分发货 2：完成发货)
   */
  private Short deliveryState;
  /**
   * 签收状态(0：未签收 1：部分签收 2：完成签收)
   */
  private Short collectState;
  /**
   * 发货省市区
   */
  private String postArea;
  /**
   * 发货详细地址
   */
  private String postAddress;
  /**
   * 我方单据图片
   */
  private String mainSrcImages;
  /**
   * 对方单据图片
   */
  private String secondSrcImages;
  /**
   * 是否已生成记录(库存记录、应收付记录等) 0:未生成 1：已生成
   */
  private Short haveRecord;
  /**
   * 订单项
   */
  protected List<DownPurchaseReturnOrderItem> items;
}
